#include <iostream>
#include <fstream>
#include <string>

#include <stdlib.h>

using namespace std;

int latin;
int squish;
int utf8;
int bad;

void test(string& line){
  const char* str = line.c_str();
  int len = line.length();

  unsigned char byte;
  for( int i=0; i<len; i++ ){
    byte = str[i];

    if( (byte & 0x80) == 0x00 ){
      latin++;
      continue;
    }


    // Possible 2 BYTE UTF8 Character
    if( (byte & 0xE0) == 0xC0 ){
      if( (len-i) >= 2 ){
        unsigned char byte2 = str[++i];  // Two Byte Character; Process the second byte
        if( (byte2 & 0xC0) == 0x80 ){
          utf8++;
        }else{
				  bad++;
					i--;
        }
      }else{
			  bad++;
      }
      continue;
    }

    // Possible 3 Byte UTF8 Character
    if( (byte & 0xF0) == 0xE0 ){
      if( (len-i) >= 3 ){
        unsigned char byte2 = str[++i];  // Process the second byte
				if( (byte2 & 0xC0) == 0x80 ){
          unsigned char byte3 = str[++i];  // Process the second byte
				  if( (byte3 & 0xC0) == 0x80 ){
					  utf8++;
					}else{
					  bad++;
						i -= 2;
					}
			  }else{
				  bad++;
					i--;
			  }
      }else{
			  bad++;
      }
      continue;
    }

    // Possible 4 Byte UTF-8 Character
		if( (byte & 0xF8) == 0xF0 ){
      if( (len-i) >= 4 ){
			  unsigned char byte2 = str[++i];  // Process the second byte
				if( (byte2 & 0xC0) == 0x80 ){
					unsigned char byte3 = str[++i];  // Process the third byte
					if( (byte3 & 0xC0) == 0x80 ){
						unsigned char byte4 = str[++i];  // Process the fourth byte
						if( (byte4 & 0xC0) == 0x80 ){
						  utf8++;
						}else{
						   bad++;
							 i -= 3;
						}
					}else{
					   bad++;
						 i -= 2;
					}
				}else{
				   bad++;
					 i--;
				}
			}else{
			   bad++;
			}
      continue;
		}
		
    if( (byte & 0xE0) == 0x80 ){
      squish++;
    }else{
      bad++;
    }
  }
}

void errorMessage(){
}

void checkFiles(char** files, int sz){
  char* filename;
 
  for( int i=1; i<sz; i++ ){
    bad = latin = squish = utf8 = 0;
		
		filename = files[i];
		cout << "Checking [" << filename << "]" << endl;
	  
    ifstream is;
    is.open (filename, ios::binary );

    string ln;
    while( !is.eof() ){
      getline(is, ln);
      test(ln);
    }
    is.close();

    cout << dec << "==> The file [" << filename << "] has:\n\t"
        << latin  << " ISO-8859-1 or UTF-8 Characters\n\t"
        << bad    << " ISO-8859-1 Only Characters\n\t"
        << squish << " Windows-1252 Characters\n\t"
        << utf8   << " UTF-8 Characters" << endl;
  }
}	


int main(int argc, char** argv){
  switch(argc){
	  case 1:
		  errorMessage();
			break;
		default:
		  checkFiles(argv, argc);
			break;
	}
	return 0;
}
